package com.yami.shop.personnft.api.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.yami.shop.bean.dto.UserImgDto;
import com.yami.shop.bean.enums.SceneType;
import com.yami.shop.bean.event.CreateTreeImgEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.bean.Minio;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.*;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.personnft.common.controller.BaseController;
import com.yami.shop.personnft.common.dto.PersonAllClassDto;
import com.yami.shop.personnft.common.model.PersonNft;
import com.yami.shop.personnft.common.model.PersonnftBrowseLog;
import com.yami.shop.personnft.common.service.PersonNftService;
import com.yami.shop.personnft.common.service.PersonShareService;
import com.yami.shop.personnft.common.service.PersonnftBrowseLogService;
import com.yami.shop.personnft.common.vo.*;
import com.yami.shop.rights.common.strategy.PersonRightsFactory;
import com.yami.shop.rights.common.vo.ProdRightDetailVo;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.security.common.util.AuthUserContext;
import com.yami.shop.service.*;
import com.yami.shop.user.common.model.UserGasInfo;
import com.yami.shop.user.common.service.UserGasInfoService;
import groovy.lang.Tuple;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * spu信息
 *
 * @author FrozenWatermelon
 * @date 2020-10-28 15:27:24
 */
@Slf4j
@RestController("appPersonnftDtcController")
@RequestMapping("/dtc/app/personnft")
@Tag(name = "app-personnftDtc信息")
@AllArgsConstructor
@EnableAsync
public class PersonnftDtcController extends BaseController {
    @Autowired
    private PersonNftService personNftService;
    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private ShopConfig shopConfig;
    @Autowired
    private DataWebService dataWebService;
    @Autowired
    private ChannelUserRelationRecordService channelUserRelationRecordService;
    @Autowired
    private ProdNftService prodNftService;
    @Autowired
    private ProductService productService;
    @Autowired
    private PersonRightsFactory personRightsFactory;
    @Autowired
    private UserGasInfoService userGasInfoService;
    @Autowired
    private PersonnftBrowseLogService personnftBrowseLogService;
    @Autowired
    private UserImgService userImgService;
    @Autowired
    private UserService userService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private AttachFileService attachFileService;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private PersonShareService personShareService;
    @Autowired
    private ProdModelService prodModelService;



    @GetMapping("/getOneClassListForConsign")
    public ServerResponseEntity<IPage<PersonNft>> getOneClassListForConsign(PageParam pageDTO, PersonNft personNft) {
        if (personNft.getUserId() == null) {
            String userId = AuthUserContext.get().getUserId();
            personNft.setUserId(userId);
        }
        if (personNft.getDawNameId() == null) {
            return ServerResponseEntity.showFailMsg("id不能为空");
        }
        personNft.setProductId(personNft.getDawNameId());
        personNft.setStatus(0);
        IPage<PersonNft> page = personNftService.page(pageDTO, personNft);
        return ServerResponseEntity.success(page);
    }

    @GetMapping("/getSecretValue")
    public ServerResponseEntity<String> getSecretValue() {
        String randomString = ParamSignUtil.getRandomString(16);
        return ServerResponseEntity.success(randomString);
    }

    /**
     * 微发行获取个人持仓DAW分类列表
     * @param personNft
     * @return dawNameId,count,denomId, dawName,dawUriType,shopName
     */
    @GetMapping("/getAllClassListByShop")
    @Operation(summary =  "获取平台信息列表", description = "分页获取平台信息列表")
    public ServerResponseEntity<IPage<PersonAllClassDto>> getAllClassListByShop(PageParam<PersonNft> page,PersonNft personNft,Long shopId) throws Exception {
//        if(ObjectUtil.isNull(shopId)){
//            throw new YamiShopBindException("yami.sys.illegalArgument");
//        }
        String userId = SecurityUtils.getUser().getUserId();
        personNft.setUserId(userId);
        personNft.setShopId(shopId);
        // 获取持仓信息
        IPage<PersonAllClassDto> allClassList = personNftService.getAllClassListByShop(page,personNft);
        return ServerResponseEntity.success(allClassList);
    }

    @GetMapping("browsePerson")
    public ServerResponseEntity<Void> browsePerson(Long prodId,String prodType){
        // 查询该用户是否点击过该持仓
        String userId = SecurityUtils.getUser().getUserId();
        PersonnftBrowseLog personnftBrowseLog = personnftBrowseLogService.getOne(new QueryWrapper<PersonnftBrowseLog>().eq("prod_id", prodId).eq("user_id", userId).eq("prod_type",prodType));
        if(ObjectUtil.isEmpty(personnftBrowseLog)){
            personnftBrowseLogService.save(PersonnftBrowseLog.builder().browseTime(new Date()).prodId(prodId).userId(userId).prodType(prodType).build());
        }else{
            personnftBrowseLog.setBrowseTime(new Date());
            personnftBrowseLogService.updateById(personnftBrowseLog);
        }

        return ServerResponseEntity.success();
    }

    /**
     *  微发行获取个人持仓个数
     * @param personNft
     * @return
     */
    @GetMapping("/getAllcountByShop")
    @Operation(summary =  "获取平台信息列表", description = "分页获取平台信息列表")
    public ServerResponseEntity<Integer> getAllcountByShop(PersonNft personNft,Long shopId)  throws Exception{
        if(ObjectUtil.isNull(shopId)){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        String userId = SecurityUtils.getUser().getUserId();
        ShopDetail shopDetailByShopId = shopDetailService.getShopDetailByShopId(shopId);
        personNft.setUserId(userId);
        personNft.setChannelCode(shopDetailByShopId.getChannelCode());
        return ServerResponseEntity.success(personNftService.listByParamCount(personNft));
    }
    /**
     * 获取个人持仓个数
     * @param personNft
     * @return
     */
    @GetMapping("/getAllcount")
    @Operation(summary =  "获取平台信息列表", description = "分页获取平台信息列表")
    public ServerResponseEntity<Integer> getAllcount(PersonNft personNft)  throws Exception{
        String userId = SecurityUtils.getUser().getUserId();
        Tuple<String> tuple = this.getChannelInfo(userId);
        if("1".equals(tuple.get(3))){
            personNft.setUserId(tuple.get(1));
            personNft.setChainCode(tuple.get(2));
            personNft.setChannelCode(tuple.get(0));
            return ServerResponseEntity.success(personNftService.listByParamCount(personNft));
        }
        return ServerResponseEntity.success(0);
    }
    /**
     * 生涯树
     * @param personNft
     * @return dawNameId,count,denomId, dawName,dawUriType,shopName
     */
    @GetMapping("/getAllClassTreeList")
    @Operation(summary =  "生涯树", description = "分页获取平台信息列表")
    public ServerResponseEntity getAllClassTreeList(PersonNft personNft) throws Exception {
        if(StrUtil.isEmpty(personNft.getOrderBy())){
            personNft.setOrderBy("1");//倒序
        }
        String userId = SecurityUtils.getUser().getUserId();
        Tuple<String> tuple = this.getChannelInfo(userId);
        if("1".equals(tuple.get(3))){
            personNft.setUserId(userId);
            personNft.setChainCode(tuple.get(2));
            personNft.setChannelCode(tuple.get(0));
            String mall4JChannel = shopConfig.getMall4JChannel();
            List<PersonTreeVO> allClassList = null;
            if(StrUtil.isNotEmpty(mall4JChannel) && StringUtils.matches(tuple.get(0), Arrays.asList(mall4JChannel.split(",")))){
                allClassList = personNftService.getAllClassTreeList2(personNft);
                if(allClassList.size()>0){
                    allClassList.stream().forEach(s->{
                        Object o = RedisUtil.get("applyIssue::" + s.getDenomId());
                        if(ObjectUtil.isNull(o)){
                            personNftService.getApplyIssueNftInfoByDenomId(s.getDenomId());
                            o = RedisUtil.get("applyIssue::" + s.getDenomId());
                        }
                        JSONObject obj = JSONObject.parseObject(o.toString());
                        s.setShortUrl(obj.getString("imgUrl"));
                        s.setDawName(obj.getString("dawName"));
                        s.setAuthor(obj.getString("author"));
                        s.setShopName(obj.getString("author"));
                    });
                }
            }else {
                allClassList = personNftService.getAllClassTreeList(personNft);
            }
            for (PersonTreeVO nft:allClassList) {
                List<PersonTreeNftVO> personTreeNftVOList = nft.getPersonTreeNftVOList();
                for (PersonTreeNftVO personTreeNftVO :personTreeNftVOList){
                    personTreeNftVO.setSceneTypeName(SceneType.getPaymentType(personTreeNftVO.getSceneType().toString()));
                }
            }
            return ServerResponseEntity.success(allClassList);
        }else{
            personNft.setUserId(tuple.get(1));
            Map<String, String> stringObjectMap = this.setRequestParame(personNft,tuple.get(0),tuple.get(2));
            String url = shopConfig.getApiGatewayUrl() + "/personnft/outapi/app/personnft/getAllClassTreeList?";
            JSONObject jsonObject = dataWebService.hutoolGetWebService(url,stringObjectMap,null,null);
            if(jsonObject.getInteger("code")== Constant.WARN){
                logger.info("获取{}",jsonObject.getString("msg"));
                return ServerResponseEntity.showFailMsg(jsonObject.getString("msg"));
            }
            if(jsonObject.getInteger("code")!= Constant.SUCCESS_CODE){
                logger.info("获取{}",jsonObject.getString("msg"));
                return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.channel.error"));
            }
            JSONArray data = jsonObject.getJSONArray("data");
            return ServerResponseEntity.success(data);
        }
    }
    /**
     * 生涯树外层分页  子查询多条件 且 改造分页需要增加下游接口等 采用原有接口组装 测试生涯树非常大后台查询时间可接受
     * @param personNft
     * @return dawNameId,count,denomId, dawName,dawUriType,shopName
     */
    @GetMapping("/getAllClassTreeListPage")
    @Operation(summary =  "生涯树", description = "分页获取平台信息列表")
    public ServerResponseEntity getAllClassTreeListPage(PageParam<PersonNft> page,PersonNft personNft) throws Exception {
        if(StrUtil.isEmpty(personNft.getOrderBy())){
            personNft.setOrderBy("1");//倒序
        }
        String userId = SecurityUtils.getUser().getUserId();
        Tuple<String> tuple = this.getChannelInfo(userId);
        if("1".equals(tuple.get(3))){
            IPage<PersonTreeVO> resAll = new PageParam<>();
            resAll.setSize(page.getSize());
            resAll.setCurrent(page.getCurrent());
            personNft.setUserId(userId);
            personNft.setChainCode(tuple.get(2));
            personNft.setChannelCode(tuple.get(0));
            String mall4JChannel = shopConfig.getMall4JChannel();
            IPage<Map<String, Object>> res = null;
            if(StrUtil.isNotEmpty(mall4JChannel) && StringUtils.matches(tuple.get(0), Arrays.asList(mall4JChannel.split(",")))){
                res = personNftService.getAllClassList2(page,personNft);
            }else{
                res = personNftService.getAllClassList(page,personNft);
            }
            if (res.getRecords().size()>0) {
                List<PersonTreeVO> allClassList = null;
                Boolean isMall4j;
                if(StrUtil.isNotEmpty(mall4JChannel) && StringUtils.matches(tuple.get(0), Arrays.asList(mall4JChannel.split(",")))){
                    isMall4j = true;
                    allClassList = personNftService.getAllClassTreeList2(personNft);
                    allClassList.stream().forEach(s->{
                        Object o = RedisUtil.get("applyIssue::" + s.getDenomId());
                        if(ObjectUtil.isNull(o)){
                            personNftService.getApplyIssueNftInfoByDenomId(s.getDenomId());
                            o = RedisUtil.get("applyIssue::" + s.getDenomId());
                        }
                        JSONObject obj = JSONObject.parseObject(o.toString());
                        s.setShortUrl(obj.getString("imgUrl"));
                        s.setDawName(obj.getString("dawName"));
                        s.setAuthor(obj.getString("author"));
                        s.setShopName(obj.getString("author"));
                    });
                }else{
                    isMall4j = false;
                    allClassList = personNftService.getAllClassTreeList(personNft);
                }
                for (PersonTreeVO nft:allClassList) {
                    List<PersonTreeNftVO> personTreeNftVOList = nft.getPersonTreeNftVOList();
                    for (PersonTreeNftVO personTreeNftVO :personTreeNftVOList){
                        personTreeNftVO.setSceneTypeName(SceneType.getPaymentType(personTreeNftVO.getSceneType().toString()));
                    }
                }
                Map<Long, PersonTreeVO> collect1;
                Map<String, PersonTreeVO> collect2;
                if(isMall4j){
                    collect1 = null;
                    collect2 = allClassList.stream().collect(Collectors.toMap(PersonTreeVO::getDenomId, Function.identity()));
                }else{
                    collect2 = null;
                    collect1 = allClassList.stream().collect(Collectors.toMap(PersonTreeVO::getProductId, Function.identity()));
                }
                List<Map<String, Object>> records = res.getRecords();
                List<PersonTreeVO> reslut = new ArrayList<>();
                records.forEach(s->{
                    if(isMall4j){
                        reslut.add(collect2.get(Long.valueOf(s.get("denomId").toString())));
                    }else{
                        reslut.add(collect1.get(Long.valueOf(s.get("productId").toString())));
                    }
                });
                resAll.setRecords(reslut);
                resAll.setPages(res.getPages());
                resAll.setTotal(res.getTotal());
            }
            return ServerResponseEntity.success(resAll);
        }else{
            IPage<JSONObject> resAll = new PageParam<>();
            resAll.setSize(page.getSize());
            resAll.setCurrent(page.getCurrent());
            personNft.setUserId(tuple.get(1));
            Map<String, String> stringObjectMap = this.setPageRequestParame(personNft, page.getCurrent(), page.getSize(), tuple.get(0),tuple.get(2));
            String url = shopConfig.getApiGatewayUrl() + "/personnft/outapi/app/personnft/getAllDomainClassList?";
            JSONObject jsonObject = dataWebService.hutoolGetWebService(url,stringObjectMap,null,null);
            if(jsonObject.getInteger("code")== Constant.WARN){
                logger.info("获取{}",jsonObject.getString("msg"));
                return ServerResponseEntity.showFailMsg(jsonObject.getString("msg"));
            }
            if(jsonObject.getInteger("code")!= Constant.SUCCESS_CODE){
                logger.info("获取{}",jsonObject.getString("msg"));
                return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.channel.error"));
            }
            IPage<Map<String, Object>> res = (IPage<Map<String, Object>>) page(jsonObject, page.getCurrent(), page.getSize());
            if(ObjectUtils.isNotEmpty(res)&&ObjectUtil.isNotEmpty(res.getRecords())){
                Map<String, String> stringObjectMap1 = this.setRequestParame(personNft,tuple.get(0),tuple.get(2));
                String url1 = shopConfig.getApiGatewayUrl() + "/personnft/outapi/app/personnft/getAllClassTreeList?";
                JSONObject jsonObject1 = dataWebService.hutoolGetWebService(url1,stringObjectMap1,null,null);
                if(jsonObject1.getInteger("code")== Constant.WARN){
                    logger.info("获取{}",jsonObject.getString("msg"));
                    return ServerResponseEntity.showFailMsg(jsonObject1.getString("msg"));
                }
                if(jsonObject1.getInteger("code")!= Constant.SUCCESS_CODE){
                    logger.info("获取{}",jsonObject1.getString("msg"));
                    return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.channel.error"));
                }
                JSONArray data = jsonObject1.getJSONArray("data");
                Map<Long,JSONObject> orderJs = data.stream().collect(Collectors.toMap(item->{
                    JSONObject js = (JSONObject)item;
                    return Long.valueOf(js.get("productId").toString());
                },item-> (JSONObject)item));
                List<JSONObject> reslut = new ArrayList<>();
                Iterator<Map<String, Object>> iterator = res.getRecords().iterator();
                while (iterator.hasNext()) {
                    Map<String, Object> map = iterator.next();
                    reslut.add(orderJs.get(Long.valueOf(map.get("productId").toString())));
                }
                resAll.setRecords(reslut);
                resAll.setPages(res.getPages());
                resAll.setTotal(res.getTotal());
            }
            return ServerResponseEntity.success(resAll);
        }

    }
    /**
     * 获取个人持仓DAW分类列表
     * @param personNft
     * @return dawNameId,count,denomId, dawName,dawUriType,shopName
     */
    @GetMapping("/getAllClassList")
    @Operation(summary =  "获取平台信息列表", description = "分页获取平台信息列表")
    public ServerResponseEntity<IPage<Map<String, Object>>> getAllClassList(PageParam<PersonNft> page,PersonNft personNft) throws Exception {
        String userId = SecurityUtils.getUser().getUserId();
//        if(StrUtil.isEmpty(personNft.getOrderBy())){
//            personNft.setOrderBy("1");//倒序
//        }
        Tuple<String> tuple = this.getChannelInfo(userId);
        if("1".equals(tuple.get(3))){
            personNft.setUserId(userId);
            personNft.setChainCode(tuple.get(2));
            personNft.setChannelCode(tuple.get(0));
            String mall4JChannel = shopConfig.getMall4JChannel();
            IPage<Map<String, Object>> res = null;
            if(StrUtil.isNotEmpty(mall4JChannel) && StringUtils.matches(tuple.get(0), Arrays.asList(mall4JChannel.split(",")))){
                res = personNftService.getAllClassList2(page,personNft);
                //添加mall4j部分信息
                List<Map<String, Object>> records = res.getRecords();
                records.stream().forEach(s->{
                    Object o = RedisUtil.get("applyIssue::" + s.get("denomId").toString());
                    if(ObjectUtil.isNull(o)){
                        personNftService.getApplyIssueNftInfoByDenomId(s.get("denomId").toString());
                        o = RedisUtil.get("applyIssue::" + s.get("denomId").toString());
                    }
                    JSONObject obj = JSONObject.parseObject(o.toString());
                    s.put("publishTime",ObjectUtil.isNotEmpty(obj.getString("createTime"))?obj.getString("createTime").substring(0,10):null);
                    s.put("shortUrl",obj.getString("imgUrl"));
                    s.put("dawName",obj.getString("dawName"));
                    s.put("author",obj.getString("author"));
                    s.put("shopName",obj.getString("author"));
                    s.put("attr",obj.getString("objType"));
                });
                res.setRecords(records);
            }else{
                res = personNftService.getAllClassList(page,personNft);
            }
            return ServerResponseEntity.success(res);
        }else{
            personNft.setUserId(tuple.get(1));
            Map<String, String> stringObjectMap = this.setPageRequestParame(personNft, page.getCurrent(), page.getSize(), tuple.get(0),tuple.get(2));
            String url = shopConfig.getApiGatewayUrl() + "/personnft/outapi/app/personnft/getAllDomainClassList?";
            JSONObject jsonObject = dataWebService.hutoolGetWebService(url,stringObjectMap,null,null);
            if(jsonObject.getInteger("code")== Constant.WARN){
                logger.info("获取{}",jsonObject.getString("msg"));
                return ServerResponseEntity.showFailMsg(jsonObject.getString("msg"));
            }
            if(jsonObject.getInteger("code")!= Constant.SUCCESS_CODE){
                logger.info("获取{}",jsonObject.getString("msg"));
                return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.channel.error"));
            }
            IPage<Map<String, Object>> res = (IPage<Map<String, Object>>) page(jsonObject, page.getCurrent(), page.getSize());
            if(ObjectUtils.isNotEmpty(res)&&ObjectUtil.isNotEmpty(res.getRecords())){
                Iterator<Map<String, Object>> iterator = res.getRecords().iterator();
                while (iterator.hasNext()) {
                    Map<String, Object> map = iterator.next();
                    Product product = productService.getSynchronizationprod(tuple.get(2), tuple.get(0), String.valueOf(map.get("productId")));
                    if (ObjectUtils.isEmpty(product)) { //删除没有同步的商品
                        iterator.remove();
                        continue;
                    }
                    map.put("dawName",product.getProdName());
                    map.put("chainCode",tuple.get(2));
                    map.put("shortUrl",product.getPic());
                    LambdaQueryWrapper<ProdNft> eq = new LambdaQueryWrapper<ProdNft>().eq(ProdNft::getProdId, product.getProdId());
                    ProdNft prodNft = prodNftService.getOne(eq);
                    if(!ObjectUtil.isNull(personNft.getIsRed()) && !personNft.getIsRed().equals(Long.valueOf(prodNft.getIsRed()))){
                        iterator.remove(); // 删除红包限制展示
                        continue;
                    }
                    map.put("author",prodNft.getAuthorName());
                    map.put("attr",prodNft.getAttr());
                    map.put("publishTime",DateUtil.format(prodNft.getCreateTime(),"yyyy/MM/dd"));
                }
            }
            return ServerResponseEntity.success(res);

        }
    }

    /**
     * 获取个人持仓目分类中具体token列表
     * @param personNft
     * @return list->tokenId shortUri
     */
    @GetMapping("/getOneClassList")
    @Operation(summary =  "获取平台信息列表", description = "分页获取平台信息列表")
    public ServerResponseEntity<IPage<PersonNft>> getOneClassList(PageParam<PersonNft> page,PersonNft personNft,String fromSource) throws Exception {
        String userId = SecurityUtils.getUser().getUserId();
        if(StrUtil.isEmpty(personNft.getOrderBy())){
            personNft.setOrderBy("1");//倒序
        }
//        Tuple<String> tuple = this.getChannelInfo(userId);
//        if("1".equals(tuple.get(3))){
//            if(personNft.getProductId()==null && StrUtil.isEmpty(personNft.getDenomId())){
//                throw new YamiShopBindException("yami.sys.illegalArgument");
//            }
//            personNft.setUserId(userId);
//            IPage<PersonNft> page1 = personNftService.page(page, personNft);
//            for (PersonNft nft:page1.getRecords()) {
//                nft.setSceneTypeName(SceneType.getPaymentType(nft.getSceneType().toString()));
//            }
//            return ServerResponseEntity.success(page1);
//        }else{
//            if(personNft.getProductId()==null){
//                throw new YamiShopBindException("yami.sys.illegalArgument");
//            }
//            personNft.setUserId(tuple.get(1));
//            if(StrUtil.isNotEmpty(fromSource) && fromSource.equals("1")){
//                LambdaQueryWrapper<Product> productId =
//                        new LambdaQueryWrapper<Product>()
//                                .eq(Product::getProdId, personNft.getProductId())
//                                .eq(Product::getChannelCode,tuple.get(0))
//                                .eq(Product::getSource,1);
//                Product product = productService.getOne(productId);
//                if(ObjectUtils.isNotEmpty(product) && product.getSource()==1){
//                    personNft.setProductId(product.getSourceId());
//                }
//            }
//            Map<String, String> stringObjectMap = this.setPageRequestParame(personNft, page.getCurrent(), page.getSize(), tuple.get(0),tuple.get(2));
//            String url = shopConfig.getApiGatewayUrl() + "/personnft/outapi/app/personnft/getOneDomainClassList?";
//            JSONObject jsonObject = dataWebService.hutoolGetWebService(url,stringObjectMap,null,null);
//            if(jsonObject.getInteger("code")== Constant.WARN){
//                logger.info("获取{}",jsonObject.getString("msg"));
//                return ServerResponseEntity.showFailMsg(jsonObject.getString("msg"));
//            }
//            if(jsonObject.getInteger("code")!= Constant.SUCCESS_CODE){
//                logger.info("获取{}",jsonObject.getString("msg"));
//                return ServerResponseEntity.showFailMsg("获取列表失败");
//            }
//            IPage<PersonNft> res = (IPage<PersonNft>) page(jsonObject, page.getCurrent(), page.getSize());
//            return ServerResponseEntity.success(res);
//        }
        if(personNft.getProductId()==null && StrUtil.isEmpty(personNft.getDenomId())){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        personNft.setUserId(userId);
        IPage<PersonNft> page1 = personNftService.page(page, personNft);
        for (PersonNft nft:page1.getRecords()) {
            nft.setSceneTypeName(SceneType.getPaymentType(nft.getSceneType().toString()));
        }
        return ServerResponseEntity.success(page1);
    }


    /**
     * 获取个人持仓详情
     * @param personNft
     * @return tokenId,denomId,dawName,dawUriType,shopName, dawUri
     */
    @GetMapping("/getOneDetail")
    @Operation(summary =  "获取平台信息列表", description = "分页获取平台信息列表")
    public ServerResponseEntity<JSONObject> getOneDetail( PersonNft personNft) throws Exception {
        if(personNft.getTokenId()==null){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        String userId = SecurityUtils.getUser().getUserId();
        Tuple<String> tuple = this.getChannelInfo(userId);
        ChannelUserRelationRecord channelAddressByChainCode = channelUserRelationRecordService.getinfoByUserIdChainCodeChannelCode(userId, tuple.get(2),tuple.get(0),tuple.get(3));
        personNft.setUserId(userId);
        PersonNftDtailfVo oneDetail = null;
        String mall4JChannel = shopConfig.getMall4JChannel();
        oneDetail = personNftService.getOneDetail(personNft);
        // 查询 扫描绑定信息
        ProdModel prodModel = prodModelService.getOne(new QueryWrapper<ProdModel>().eq("prod_id", oneDetail.getProductId()));
        if(ObjectUtil.isNotEmpty(prodModel)){
            oneDetail.setIsScan(1);
            oneDetail.setScanImg(prodModel.getScanImg());
            oneDetail.setScanModel(prodModel.getScanModel());
        }
        if(ObjectUtil.isNotEmpty(oneDetail.getSourceUrl())){
            JSONObject jsonObject = JSONObject.parseObject(oneDetail.getDawUri());
            jsonObject.put("sourceFile", oneDetail.getSourceUrl());
            oneDetail.setDawUri(jsonObject.toJSONString());
        }
        // 获取分享信息
        PersonShareVo personShare = personShareService.getDetailByTokenId(personNft.getTokenId());
        if(ObjectUtil.isNotEmpty(personShare)){
//                if(ObjectUtil.isNotEmpty(personShare.getImgUrl())){
//                    oneDetail.setListImg(personShare.getImgUrl());
//                }
            oneDetail.setBlessing(personShare.getBlessing());
            oneDetail.setVoiceTime(personShare.getVoiceTime());
            oneDetail.setVoiceUrl(personShare.getVoiceUrl());
            oneDetail.setColorData(personShare.getColorData());
        }
        if(ObjectUtil.isNotEmpty(oneDetail.getRightsIds())){
            // 补充权益信息
            List<ProdRightDetailVo> prodRightVos = personRightsFactory.getRightsDetails(oneDetail.getTokenId());
            List<ProdRightVo> prodRightVos1 = BeanUtil.copyToList(prodRightVos, ProdRightVo.class);
            oneDetail.setProdRightVos(ObjectUtil.isNull(prodRightVos1)?new ArrayList<>():prodRightVos1);
            oneDetail.setRightCount(oneDetail.getProdRightVos().size());
            // 权益使用次数
            oneDetail.setRightUserCount(oneDetail.getProdRightVos().stream().filter(s -> "1".equals(s.getStatus())).count());
        }
            oneDetail.setAdress(channelAddressByChainCode.getAddress());
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(oneDetail, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
            data.put("source",tuple.get(3));
        return ServerResponseEntity.success(data);


//
//        if("1".equals(tuple.get(3))){
//            PersonNftDtailfVo oneDetail = null;
//            String mall4JChannel = shopConfig.getMall4JChannel();
//            if(StrUtil.isNotEmpty(mall4JChannel) && StringUtils.matches(tuple.get(0), Arrays.asList(mall4JChannel.split(",")))){
//                oneDetail = personNftService.getOneDetail1(personNft);
//                Object o = RedisUtil.get("applyIssue::" + oneDetail.getDenomId());
//                if(ObjectUtil.isNull(o)){
//                    personNftService.getApplyIssueNftInfoByDenomId(oneDetail.getDenomId());
//                    o = RedisUtil.get("applyIssue::" + oneDetail.getDenomId());
//                }
//                JSONObject obj = JSONObject.parseObject(o.toString());
//                oneDetail.setAuthor(obj.getString("author"));
//                oneDetail.setShopName(obj.getString("author"));
//                oneDetail.setAttr(Long.valueOf(obj.getString("objType")));
//                JSONObject obj1 = new JSONObject();
//                obj1.put("sourceFile",obj.getString("imgUrl"));
//                oneDetail.setDawUri(obj1.toJSONString());
//                oneDetail.setDawUriType(Long.valueOf(obj.getString("objType")));
//            }else{
//                oneDetail = personNftService.getOneDetail(personNft);
//                // 查询 扫描绑定信息
//                ProdModel prodModel = prodModelService.getOne(new QueryWrapper<ProdModel>().eq("prod_id", oneDetail.getProductId()));
//                if(ObjectUtil.isNotEmpty(prodModel)){
//                    oneDetail.setIsScan(1);
//                    oneDetail.setScanImg(prodModel.getScanImg());
//                    oneDetail.setScanModel(prodModel.getScanModel());
//                }
//                if(ObjectUtil.isNotEmpty(oneDetail.getSourceUrl())){
//                    JSONObject jsonObject = JSONObject.parseObject(oneDetail.getDawUri());
//                    jsonObject.put("sourceFile", oneDetail.getSourceUrl());
//                    oneDetail.setDawUri(jsonObject.toJSONString());
//                }
//            }
//            // 获取分享信息
//            PersonShareVo personShare = personShareService.getDetailByTokenId(personNft.getTokenId());
//            if(ObjectUtil.isNotEmpty(personShare)){
////                if(ObjectUtil.isNotEmpty(personShare.getImgUrl())){
////                    oneDetail.setListImg(personShare.getImgUrl());
////                }
//                oneDetail.setBlessing(personShare.getBlessing());
//                oneDetail.setVoiceTime(personShare.getVoiceTime());
//                oneDetail.setVoiceUrl(personShare.getVoiceUrl());
//                oneDetail.setColorData(personShare.getColorData());
//            }
//            if(ObjectUtil.isNotEmpty(oneDetail.getRightsIds())){
//                // 补充权益信息
//                List<ProdRightDetailVo> prodRightVos = personRightsFactory.getRightsDetails(oneDetail.getTokenId());
//                List<ProdRightVo> prodRightVos1 = BeanUtil.copyToList(prodRightVos, ProdRightVo.class);
//                oneDetail.setProdRightVos(ObjectUtil.isNull(prodRightVos1)?new ArrayList<>():prodRightVos1);
//                oneDetail.setRightCount(oneDetail.getProdRightVos().size());
//                // 权益使用次数
//                oneDetail.setRightUserCount(oneDetail.getProdRightVos().stream().filter(s -> "1".equals(s.getStatus())).count());
//            }
////            oneDetail.setAdress(channelAddressByChainCode.getAddress());
//            JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(oneDetail, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
////            data.put("source",tuple.get(3));
//            return ServerResponseEntity.success(data);
//        }else{
//            JSONObject dawUriJson = new JSONObject();
//            Map<String, String> stringObjectMap = this.setRequestParame(personNft,tuple.get(0),tuple.get(2));
//            String url = shopConfig.getApiGatewayUrl() + "/personnft/outapi/app/personnft/getTokenDetail?";
//            JSONObject jsonObject = dataWebService.hutoolGetWebService(url, stringObjectMap,null,null);
//            if(jsonObject.getInteger("code")== Constant.WARN){
//                logger.info("获取{}",jsonObject.getString("msg"));
//                return ServerResponseEntity.showFailMsg(jsonObject.getString("msg"));
//            }
//            if(jsonObject.getInteger("code")!= Constant.SUCCESS_CODE){
//                logger.info("获取{}",jsonObject.getString("msg"));
//                return ServerResponseEntity.showFailMsg("获取详情失败");
//            }
//            JSONObject data = jsonObject.getJSONObject("data");
//            data.put("isWatermark",0);
////            data.put("source",tuple.get(3));
////            data.put("adress",channelAddressByChainCode.getAddress());
//            if(ObjectUtils.isNotEmpty(data)){
//                Product product = productService.getSynchronizationprod(tuple.get(2), tuple.get(0), String.valueOf(data.get("productId")));
//                if(ObjectUtils.isNotEmpty(product)){
//                    data.put("dawName",product.getProdName());
////                    data.put("shortUrl",product.getPic());
//                    data.put("picImg",product.getPic());
//                    data.put("listImg",product.getPic());
//                    LambdaQueryWrapper<ProdNft> eq = new LambdaQueryWrapper<ProdNft>().eq(ProdNft::getProdId, product.getProdId());
//                    ProdNft prodNft = prodNftService.getOne(eq);
//                    data.put("author",prodNft.getAuthorName());
//                    data.put("authorImg",prodNft.getAuthorImg());
//                    data.put("attr",prodNft.getAttr());
//                    data.put("rightUserCount",0);
//                    data.put("rightCount",0);
//                    data.put("levelName","");
//                    data.put("levelIcon","");
//                    data.put("prodRightVos",new ArrayList<>());
//                    // 下游如果包含 模型数据 加载模型
//                    if(ObjectUtil.isNotEmpty(jsonObject.getJSONObject("data").getJSONObject("file3D")) && ObjectUtil.isNotEmpty(jsonObject.getJSONObject("data").getJSONObject("file3D").getString("glbUrl"))){
//                        data.put("dawUriType","7");
//                        dawUriJson.put("sourceFile",jsonObject.getJSONObject("data").getJSONObject("file3D").getString("glbUrl"));
//                        data.put("dawUri",dawUriJson.toJSONString());
//                    }
//                    // 下游默认图片
//                    else{
//                        dawUriJson.put("sourceFile",data.getString("shortUrl"));
//                        data.put("dawUriType",data.getString("dawUriType"));
//                        data.put("dawUri",dawUriJson.toJSONString());
//                    }
//                }
//            }






    }
    /**
     * 1转增2划转校验  是否可以
     * @param personNft
     * @return
     * @throws Exception
     */
    @GetMapping("/IstransferToOthers")
    @Operation(summary =  "是否支持转增", description = "个人持仓")
    public ServerResponseEntity IstransferToOthers(PersonNft personNft,String type) throws Exception {
        if (personNft.getProductId() == null) {
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        ProdNft dataByProdId = null;
        try {
            String userId = SecurityUtils.getUser().getUserId();
            Long productId = personNft.getProductId();
            Tuple<String> tuple = this.getChannelInfo(userId);
            if("2".equals(tuple.get(3))){
                Product synchronizationprod = productService.getSynchronizationprod(tuple.get(2), tuple.get(0), String.valueOf(productId));
                productId = synchronizationprod.getProdId();
            }
            dataByProdId = prodNftService.getDataByProdId(productId);
        }catch (Exception e){
            return ServerResponseEntity.showFailMsg("该资产目前不支持");
        }
        if("1".equals(type)){
            if(dataByProdId.getIsPresenter()==0 ){
                return ServerResponseEntity.showFailMsg("该资产目前不支持");
            }
            if(DateUtil.compare(DateUtil.date(), dataByProdId.getPresenterTime()) <0){
                return ServerResponseEntity.showFailMsg("该资产目前时间未到");
            }
        }
        //划转
        else{
            if(dataByProdId.getIsTransfer()==0 ){
                return ServerResponseEntity.showFailMsg("该资产目前不支持");
            }
            if(DateUtil.compare(DateUtil.date(), dataByProdId.getTransferTime()) <0){
                return ServerResponseEntity.showFailMsg("该资产目前时间未到");
            }
        }
        return ServerResponseEntity.success();
    }

    /**
     * 获取可转增数量和不可转增数
     * @param personNft
     * @return
     * @throws Exception
     */
    @GetMapping("/transferToOthersAllCount")
    @Operation(summary =  "转增数量", description = "个人持仓")
    public ServerResponseEntity transferToOthersAllCount(PersonNft personNft) throws Exception {
        if(personNft.getProductId()==null ){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        String userId = SecurityUtils.getUser().getUserId();
        Tuple<String> tuple = this.getChannelInfo(userId);
        //校验是否可以转增
        Long productId = personNft.getProductId();
        if("2".equals(tuple.get(3))){
            Product synchronizationprod = productService.getSynchronizationprod(tuple.get(2), tuple.get(0), String.valueOf(productId));
            productId = synchronizationprod.getProdId();
        }
        ProdNft dataByProdId = prodNftService.getDataByProdId(productId);
        if(ObjectUtil.isNull(dataByProdId)){
            return ServerResponseEntity.showFailMsg("该资产查询不到信息");
        }
        if(dataByProdId.getIsPresenter()==0 ){
            return ServerResponseEntity.showFailMsg("该资产目前不支持");
        }
        if(DateUtil.compare(DateUtil.date(), dataByProdId.getPresenterTime()) <0){
            return ServerResponseEntity.showFailMsg("该资产目前时间未到");
        }
        if("1".equals(tuple.get(3))){
            personNft.setUserId(userId);
            JSONObject stringObjectMap = personNftService.transferToOthersAllCount(personNft);
            return ServerResponseEntity.success(stringObjectMap);
        }else{
            JSONObject jSONObject = new JSONObject();
            Integer gas = 0;
            UserGasInfo one = userGasInfoService.getOne(new LambdaQueryWrapper<UserGasInfo>().eq(UserGasInfo::getUserId, userId));
            if (one != null) {
                gas = one.getGasNumber();
            }
            jSONObject.put("gasCount", gas);
            return ServerResponseEntity.success(jSONObject);
        }
    }

    /**
     * 获取可划转数量和不可划转数
     * @param personNft
     * @return
     * @throws Exception
     */
    @GetMapping("/transferAllCount")
    @Operation(summary =  "划转数量", description = "个人持仓")
    public ServerResponseEntity transferAllCount(PersonNft personNft) throws Exception {
        if(personNft.getProductId()==null ){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        String userId = SecurityUtils.getUser().getUserId();
        Tuple<String> tuple = this.getChannelInfo(userId);
        //校验是否可以转增
        Long productId = personNft.getProductId();
        if("2".equals(tuple.get(3))){
            Product synchronizationprod = productService.getSynchronizationprod(tuple.get(2), tuple.get(0), String.valueOf(productId));
            productId = synchronizationprod.getProdId();
        }
        ProdNft dataByProdId = prodNftService.getDataByProdId(productId);
        if(ObjectUtil.isNull(dataByProdId)){
            return ServerResponseEntity.showFailMsg("该资产查询不到信息");
        }
        if(dataByProdId.getIsTransfer()==0 ){
            return ServerResponseEntity.showFailMsg("该资产目前不支持");
        }
        if(DateUtil.compare(DateUtil.date(), dataByProdId.getTransferTime()) <0){
            return ServerResponseEntity.showFailMsg("该资产目前时间未到");
        }
        if("1".equals(tuple.get(3))){
            personNft.setUserId(userId);
            personNft.setDay(ObjectUtil.isNull(dataByProdId.getTransferPreDayNum())?0l:dataByProdId.getTransferPreDayNum());
            JSONObject stringObjectMap = personNftService.transferAllCount(personNft);
            return ServerResponseEntity.success(stringObjectMap);
        }else{
            JSONObject jSONObject = new JSONObject();
            Integer gas = 0;
            UserGasInfo one = userGasInfoService.getOne(new LambdaQueryWrapper<UserGasInfo>().eq(UserGasInfo::getUserId, userId));
            if (one != null) {
                gas = one.getGasNumber();
            }
            jSONObject.put("gasCount", gas);
            return ServerResponseEntity.success(jSONObject);
        }
    }

    /**
     *
     * @param personNftApply
     * @return
     * @throws Exception
     */
    @GetMapping("/gettest")
    @Operation(summary =  "藏品冻结", description = "个人持仓")
    public ServerResponseEntity gettest(PersonNftApply personNftApply) throws Exception {
            Map<String,String> obj = new HashMap<>();
            obj.put("userId",personNftApply.getUserId());
            obj.put("toUserId",personNftApply.getToUserId());
            obj.put("channelCode",personNftApply.getChannelCode());
            obj.put("chainCode",personNftApply.getChainCode());
            obj.put("count",personNftApply.getCount().toString());
            obj.put("productId",personNftApply.getProductId().toString());
            obj.put("sceneType",personNftApply.getSceneType().toString());

            String url = shopConfig.getApiGatewayUrl() + "/personnft/outapi/app/personnftApply/freeze?";
            JSONObject jsonObject = dataWebService.hutoolPostWebService(url, obj,null,null);
            if(jsonObject.getInteger("code")== Constant.WARN){
                logger.info("获取{}",jsonObject.getString("msg"));
                return ServerResponseEntity.showFailMsg(jsonObject.getString("msg"));
            }
            if(jsonObject.getInteger("code")!= Constant.SUCCESS_CODE){
                logger.info("获取{}",jsonObject.getString("msg"));
                return ServerResponseEntity.showFailMsg("冻结失败");
            }
            log.info(jsonObject.getString("applyId"));
            log.info(jsonObject.getString("tokensIds"));
            log.info(jsonObject.getString("denomId"));
             log.info(jsonObject.getString("productCodes"));
            return ServerResponseEntity.success(jsonObject);
    }

    /**
     *
     * @param personNftApply
     * @return
     * @throws Exception
     */
    @GetMapping("/gettest1")
    @Operation(summary =  "藏品解冻", description = "个人持仓")
    public ServerResponseEntity gettest1(PersonNftApply personNftApply) throws Exception {
        Map<String,String> obj = new HashMap<>();
        obj.put("id",personNftApply.getId());
        obj.put("channelCode",personNftApply.getChannelCode().toString());
        obj.put("status",personNftApply.getStatus().toString());

        String url = shopConfig.getApiGatewayUrl() + "/personnft/outapi/app/personnftApply/unFreeze?";
        JSONObject jsonObject = dataWebService.hutoolPostWebService(url, obj,null,null);
        if(jsonObject.getInteger("code")!= Constant.SUCCESS_CODE){
            logger.info("获取{}",jsonObject.getString("msg"));
            throw new YamiShopBindException(jsonObject.getString("msg"));
        }
        return ServerResponseEntity.success(jsonObject);
    }

    /**
     *
     * @param personNftApply
     * @return
     * @throws Exception
     */
    @GetMapping("/gettest2")
    @Operation(summary =  "藏品资产转移", description = "个人持仓")
    public ServerResponseEntity gettest2(PersonNftApply personNftApply) throws Exception {
        Map<String,String> obj = new HashMap<>();
        obj.put("id",personNftApply.getId());
        obj.put("type","1");
        obj.put("channelCode",personNftApply.getChannelCode().toString());
        String url = shopConfig.getApiGatewayUrl() + "/personnft/outapi/app/personnftApply/transferPerson?";
        JSONObject jsonObject = dataWebService.hutoolPostWebService(url, obj,null,null);
        if(jsonObject.getInteger("code")!= Constant.SUCCESS_CODE){
            logger.info("获取{}",jsonObject.getString("msg"));
            throw new YamiShopBindException(jsonObject.getString("msg"));
        }
        return ServerResponseEntity.success(jsonObject);
    }

    @GetMapping("getTreeImgStatus")
    public ServerResponseEntity<UserImgDto> getTreeImgStatus() {
        // 获取生涯树图片状态
        String userId = SecurityUtils.getUser().getUserId();
        Tuple<String> channelInfo = this.getChannelInfo(userId);
        UserImg one = userImgService.getOne(
                new QueryWrapper<UserImg>()
                        .eq("user_id", userId)
                        .eq("type", 1)
                        .eq("channel_code",channelInfo.get(0))
                        .eq("chain_code",channelInfo.get(2))
                        .eq("chain_type",channelInfo.get(3)));
        // 0无图片 1 完成 2 生成中
        if(ObjectUtil.isEmpty(one)){
            one = UserImg.builder().status("0").build();
        }
        return ServerResponseEntity.success(BeanUtil.copyProperties(one, UserImgDto.class));
    }

    @GetMapping("createTreeImg")
    public ServerResponseEntity<Void> createTreeImg(PersonNft personNft) throws Exception {
        String userId = SecurityUtils.getUser().getUserId();
        // 判断图片状态
        Tuple<String> tuple = this.getChannelInfo(userId);
        UserImg one = userImgService.getOne(
                new QueryWrapper<UserImg>()
                        .eq("user_id", userId)
                        .eq("type", 1)
                        .eq("channel_code",tuple.get(0))
                        .eq("chain_code",tuple.get(2))
                        .eq("chain_type",tuple.get(3)));
        if(ObjectUtil.isNotEmpty(one) && "2".equals(one.getStatus())){
            return ServerResponseEntity.showFailMsg("图片生成中");
        }
        Map<String, Object> mp = new HashMap<>();
        // 获取Tree数据
        List<PersonTreeVO> allClassList = new ArrayList<>();
        if(StrUtil.isEmpty(personNft.getOrderBy())){
            personNft.setOrderBy("1");//倒序
        }
        if("1".equals(tuple.get(3))){
            personNft.setUserId(userId);
            personNft.setChainCode(tuple.get(2));
            personNft.setChannelCode(tuple.get(0));
            String mall4JChannel = shopConfig.getMall4JChannel();
            if(StrUtil.isNotEmpty(mall4JChannel) && StringUtils.matches(tuple.get(0), Arrays.asList(mall4JChannel.split(",")))){
                allClassList = personNftService.getAllClassTreeList2(personNft);
                if(allClassList.size()>0){
                    allClassList.stream().forEach(s->{
                        Object o = RedisUtil.get("applyIssue::" + s.getDenomId());
                        if(ObjectUtil.isNull(o)){
                            personNftService.getApplyIssueNftInfoByDenomId(s.getDenomId());
                            o = RedisUtil.get("applyIssue::" + s.getDenomId());
                        }
                        JSONObject obj = JSONObject.parseObject(o.toString());
                        s.setShortUrl(obj.getString("imgUrl"));
                        s.setDawName(obj.getString("dawName"));
                        s.setAuthor(obj.getString("author"));
                        s.setShopName(obj.getString("author"));
                    });
                }
            }else {
                allClassList = personNftService.getAllClassTreeList(personNft);
            }
            for (PersonTreeVO nft:allClassList) {
                List<PersonTreeNftVO> personTreeNftVOList = nft.getPersonTreeNftVOList();
                for (PersonTreeNftVO personTreeNftVO :personTreeNftVOList){
                    personTreeNftVO.setSceneTypeName(SceneType.getPaymentType(personTreeNftVO.getSceneType().toString()));
                }
            }
        }else {
            personNft.setUserId(tuple.get(1));
            Map<String, String> stringObjectMap = this.setRequestParame(personNft, tuple.get(0), tuple.get(2));
            String url = shopConfig.getApiGatewayUrl() + "/personnft/outapi/app/personnft/getAllClassTreeList?";
            JSONObject jsonObject = dataWebService.hutoolGetWebService(url, stringObjectMap, null, null);
            if (jsonObject.getInteger("code") == Constant.WARN) {
                logger.info("获取{}", jsonObject.getString("msg"));
            }
            if (jsonObject.getInteger("code") != Constant.SUCCESS_CODE) {
                logger.info("获取{}", jsonObject.getString("msg"));
            }
            allClassList = JSONArray.parseArray(jsonObject.getString("data"), PersonTreeVO.class);
        }
        if(ObjectUtil.isEmpty(allClassList) || allClassList.isEmpty()){
            return ServerResponseEntity.showFailMsg("无导出数据");
        }
        ShopDetail shopDetailByShopCode = shopDetailService.getShopDetailByShopCode(tuple.get(0));

        mp.put("shopShortName", shopDetailByShopCode.getShopShortName());
        mp.put("mapList", allClassList);
        // 获取用户信息
        User userDetail = userService.getUserDetail(userId);

        mp.put("userName", StringEscapeUtils.escapeHtml4(userDetail.getNickName()));
        mp.put("startYear", allClassList.get(allClassList.size() - 1).getYearStr());

//        SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd");
        mp.put("startMonthDay", allClassList.get(allClassList.size() - 1).getMonthDayStr());

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
        mp.put("endTime", sdf2.format(new Date()));

        // 图片访问地址
        Minio sysConfigObject = sysConfigService.getSysConfigObject(Constant.MINIO_OSS_CONFIG, Minio.class);
        mp.put("sourceUrl", sysConfigObject.getEndpoint() + "/" + sysConfigObject.getBucketName() + "/");
        if(ObjectUtil.isEmpty(one)){
            one = UserImg.builder().status("2").userId(userId).type("1").chainCode(tuple.get(2)).channelCode(tuple.get(0)).chainType(tuple.get(3)).build();
            userImgService.save(one);
        }else {
            // 删除旧数据 --- minio 删除
            attachFileService.deleteFile(one.getSourceUrl());
            one.setStatus("2");
            one.setSourceUrl("");
            userImgService.updateById(one);
        }
        String html = FreemarkerUtil.generate("test.ftl", mp);
        applicationContext.publishEvent(new CreateTreeImgEvent(html,one));

        return ServerResponseEntity.success();
    }


    @GetMapping("deleteTreeImg")
    public ServerResponseEntity<Void> deleteTreeImg(){
        UserImg one = userImgService.getOne(new QueryWrapper<UserImg>().eq("user_id", SecurityUtils.getUser().getUserId()).eq("type", 1));
        // 没有生成图片数据
        if(ObjectUtil.isEmpty(one)){
            return ServerResponseEntity.success();
        }
        if("1".equals(one.getStatus())){
            attachFileService.deleteFile(one.getSourceUrl());
        }
        userImgService.removeById(one);
        return ServerResponseEntity.success();
    }

}
